package com.bionic.banking.logic.controller;

import com.bionic.banking.core.entity.User;
import com.bionic.banking.dao.IUserDao;
import com.bionic.banking.dao.classes.UserDaoImpl;
import com.bionic.banking.dao.connection.LoggerLoader;
import com.bionic.banking.logic.IUserController;
import com.bionic.banking.logic.exception.InvalidParameterException;
import java.sql.SQLException;
import org.apache.log4j.Logger;

public class UserController extends AbstractBean<User> implements IUserController {

    private static final Logger logger = LoggerLoader.getLogger(UserController.class);

    @Override
    protected IUserDao getDaoObject() {
        return new UserDaoImpl();
    }

    public UserController() throws InstantiationException, IllegalAccessException {
        super();
    }

    @Override
    public Boolean create(User entity) throws SQLException, InvalidParameterException {
        String error = null;
        if (entity.getLogin() == null) {
            error = "null Login";
            throw new InvalidParameterException(error);
        } else if (getByLogin(entity.getLogin()) != null) {
            error = "user with login " + entity.getLogin() + " already exists";
            logger.error(error);
            throw new InvalidParameterException(error);
        }
        return super.create(entity);
    }

    @Override
    public User getByLogin(String login) throws SQLException {
        return getDaoObject().findByLogin(login);
    }

    @Override
    public User getByEmail(String email) throws Exception {
        return getDaoObject().findByEmail(email);
    }

    @Override
    public boolean verify(String login, String password) throws SQLException {
        User user = getByLogin(login);
        if (user == null) {
            return false;
        }
        return user.getPassword().equals(password);
    }
}
